<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>封装自己的$</title>
    <style>
        div {
            width: 100px;
            height: 100px;
            margin:10px auto;
            background-color: #369;
        }
    </style>
    <script>
        window.onload = function () {
            function $(str) {
                var s = str.charAt(0);
                var ss = str.substr(1);
                switch (s){
                    case "#":
                        return document.getElementById(ss);
                    break;
                    case ".":
                        return getClass(ss);
                    break;
                    default :
                        return document.getElementsByTagName(str);
                        break;
                }
            }


            var demos = $(".demo");
            for (var i = 0; i < demos.length; i++) {
                var obj = demos[i];
                obj.style.backgroundColor = "#ff705e";
            }
        }


        function getClass(classname) {
            if (document.getElementsByClassName){
                return document.getElementsByClassName(classname);
            }

            var attr = [];
            var elements = document.getElementsByTagName("*");
            for (var i = 0; i < elements.length; i++) {
                var obj = elements[i];
                var objCN = obj.className;
                //var pattern = new RegExp(classname,"g");
                var pattern = new RegExp("(^| )("+classname+")( |$)","g");
                if(pattern.test(objCN)){
                    attr.push(obj);
                }
            }
            return attr;
        }
    </script>

</head>
<body>
    <div class="demo"></div>
    <div></div>
    <div class="demo1"></div>
    <div></div>
    <div class="demo test"></div>
    <div class="test1 demo test"></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
</body>
</html>